package com.ysstech.common.util.imgutil;

import java.io.File;

import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.fileutil.FastDFSClient;
import com.ysstech.common.util.fileutil.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片上传
 */
public class ImageUploadUtil {
    private static final int MAX_POST_IMAGE_SIZE = 10 * 1024 * 1024;

    public static String uploadImage(MultipartFile file, String oldImageId) throws Exception {
        File filenew = null;
        try {
            if (file.isEmpty()) {
                throw new BusinessException("文件为空，请稍后重试！");
            }
            //判断文件的后缀和大小
            long fileSize = file.getSize();
            if (fileSize > MAX_POST_IMAGE_SIZE) {
                throw new BusinessException("图片大小超过10M，请重新选择上传！");
            }
            String isRealImageStr = ImageUtil.isRealImage(file.getBytes());
            if (null == isRealImageStr) {
                throw new BusinessException("上传的不是图片，请重新选择上传！");
            }
            //上传到服务器
            filenew = FileUtil.MultipartFileToFile(file);
            if (null == filenew) {
                throw new BusinessException("获取文件失败，请稍后重试！");
            }
            String path = FastDFSClient.uploadImage(filenew, oldImageId);
            if (StringUtils.isBlank(path)) {
                throw new BusinessException("上传文件失败，请稍后重试！");
            }
            return path;
        } catch (BusinessException ex) {
            throw new BusinessException(ex.getMessage());
        } finally {
            FileUtil.delteTempFile(filenew);
        }
    }
}
